package com.wfs.suanfa.nio.demo;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: wfs
 * @Date: 2020/4/17 11:09
 * @Description:
 */
public class BufferTest {
    public static void main(String[] args) {
        try {
            RandomAccessFile randomAccessFile=new RandomAccessFile("a.txt","rw");
            ByteBuffer header = ByteBuffer.allocate(2);
            ByteBuffer body   = ByteBuffer.allocate(3);
            header.put((byte)65);
            header.put((byte)66);
            body.put((byte)000);
            ByteBuffer[] bufferArray = { header, body };
            //读
            FileChannel channel = randomAccessFile.getChannel();
           /* long read = channel.read(bufferArray);
            while (read!=-1){
                for (ByteBuffer byteBuffer : bufferArray) {
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()){
                        System.out.print((char)byteBuffer.get());
                    }
                    byteBuffer.clear();
                    System.out.println();
                    channel.read(bufferArray);
                }
                read = channel.read(bufferArray);
            }*/
           //写入操作
            header.flip();
            channel.write(header);
            //randomAccessFile.writeBytes("123456");
            long position = channel.position();
            channel.close();
            randomAccessFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
